package com.bigfreakindeals.Protocols.SoapHandlers;

import java.io.IOException;
import java.util.Vector;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.bigfreakindeals.Application.ApplicationEx;
import com.bigfreakindeals.Common.Constant;
import com.bigfreakindeals.Models.UserProfile;

public class FbLoginHandler {

	static final String STATUS = "status";

	static final String ERROR = "error";

	static Boolean isLogin;

	UserProfile userProfile = new UserProfile();
	String feedUrl;

	private static final String SOAP_ACTION = "1";
	private static final String METHOD_NAME = "bigfreakindeals";
	private static final String NAMESPACE = "1";

	Context context;

	public FbLoginHandler(String feedUrl, Context context) {
		this.feedUrl = feedUrl;
		this.context = context;
		parse();
	}

	public void parse() {

		try {

			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.setOutputSoapObject(request);

			HttpTransportSE androidHttpTransport = new HttpTransportSE(feedUrl);

			try {
				androidHttpTransport.call(SOAP_ACTION, envelope);
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}

			SoapObject response = (SoapObject) envelope.getResponse();

			Log.i("LOGIN-parent: ", response.toString());

			String loginResponse = response.getProperty(STATUS).toString();
			if (loginResponse != null && loginResponse.length() > 0) {
				if (loginResponse.contentEquals("false")) {
					isLogin = false;
				} else {
					isLogin = true;
				}
			}
			userProfile.setLogin(isLogin);
			
			if (!isLogin) {
				String error = response.getProperty(ERROR).toString();
				Intent intent = new Intent(Constant.EVENTS_LOGINERROR);
				intent.putExtra(Constant.TAG_WEBSERVICE_ERROR_MESSAGE, error.substring(0, error.indexOf("SELECT")));
				ApplicationEx.getInstance().sendBroadcast(intent);
				return;
			}

		} catch (IOException e1) {
			// TODO Auto-generated catch block

			Intent intent = new Intent(Constant.EVENTS_LOGINERROR);
			intent.putExtra(Constant.EVENTS_HTTPCONNECTION_MESSAGE, Constant.HTTPCONNECTION_ERROR_MESSAGE);
			ApplicationEx.getInstance().sendBroadcast(intent);

		} catch (Exception e1) {

			Intent intent = new Intent(Constant.EVENTS_LOGINERROR);
			intent.putExtra(Constant.EVENTS_HTTPCONNECTION_MESSAGE, Constant.HTTPCONNECTION_ERROR_MESSAGE);
			ApplicationEx.getInstance().sendBroadcast(intent);
		}

	}
}
